<template>
  <div class="sign-management-page">
    <!-- 顶部培训班信息 -->
    <div class="top-info">
      <span>培训班编号：{{trainingClassCode}}</span>
      <span>培训班名称：{{className}}</span>
      <span>签到时间：{{checkinTime}}</span>
      <span>签到地点：{{checkinLocation}}</span>
    </div>

    <!-- 搜索区域 -->
    <div class="search-area" v-show="showSearch">
      <el-form inline :model="searchForm" class="search-form">
        <el-form-item label="姓名">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入姓名"
            class="search-input"
          />
        </el-form-item>
        <el-form-item label="手机号码">
          <el-input
            v-model="searchForm.phone"
            placeholder="请输入手机号码"
            class="search-input"
            maxlength="11"
          />
        </el-form-item>
        <el-form-item label="证件编号">
          <el-input
            v-model="searchForm.idCard"
            placeholder="请输入证件编号"
            class="search-input"
          />
        </el-form-item>
        <el-form-item label="签到状态">
          <el-select
            v-model="searchForm.signStatus"
            placeholder="选择签到状态"
            class="search-select"
          >
            <el-option label="全部" value="" />
            <el-option label="已签到" value="1" />
            <el-option label="未签到" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="operation-buttons">
      <el-button @click="handleExport">导出</el-button>
      <el-button
        type="primary"
        @click="showNoticeDialog = true"
        :disabled="selectedRows.length === 0"
      >
        <i class="el-icon-bell"></i> 学员通知
      </el-button>
      <el-button
        type="primary"
        @click="handleBatchSetSign(true)"
        :disabled="selectedRows.length === 0"
      >设为已签到</el-button>
      <el-button
        type="primary"
        @click="handleBatchSetSign(false)"
        :disabled="selectedRows.length === 0"
      >设为未签到</el-button>
      <el-button
        type="primary"
        @click="handleRemark"
        :disabled="selectedRows.length !== 1"
      >备注</el-button>
      <el-button @click="showSearch = !showSearch">
        {{ showSearch ? '隐藏搜索' : '显示搜索' }}
      </el-button>
      <el-button @click="handleRefresh">刷新</el-button>
    </div>

    <!-- 签到结果表格 -->
    <el-table
      ref="signTable"
      :data="paginatedList"
      border
      stripe
      size="mini"
      style="width: 100%; margin-bottom: 16px;"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center"></el-table-column>
      <el-table-column prop="name" label="姓名" width="100" align="center"></el-table-column>
      <el-table-column prop="idCard" label="证件编号" width="180" align="center"></el-table-column>
      <el-table-column prop="phone" label="电话" width="130" align="center"></el-table-column>
      <el-table-column label="签到状态" align="center" width="120">
        <template #default="scope">
          <span
            :class="scope.row.signStatus === '1' ? 'tag_1' : 'tag_0'"
          >
            {{ scope.row.signStatus === '1' ? '已签到' : '未签到' }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="备注" align="left"></el-table-column>
      <el-table-column label="操作" align="center" width="120">
        <template #default="scope">
          <el-button
            type="text"
            @click="handleSingleSetSign(scope.row, false)"
            v-if="scope.row.signStatus === '1'"
          >设为未签到</el-button>
          <el-button
            type="text"
            @click="handleSingleSetSign(scope.row, true)"
            v-if="scope.row.signStatus === '0'"
          >设为已签到</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentPageChange"
      :current-page="pagination.currentPage"
      :page-sizes="[10, 20, 50]"
      :page-size="pagination.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="totalCount"
      size="mini"
      style="text-align: right; margin-top: 8px;"
    />

    <!-- 学员通知弹窗 -->
    <el-dialog
      title="发送学员通知"
      :visible.sync="showNoticeDialog"
      width="600px"
    >
      <el-form
        ref="noticeForm"
        :model="noticeForm"
        :rules="noticeRules"
        label-width="100px"
      >
        <el-form-item label="通知对象" disabled>
          <div class="recipient-list">
            <el-tag
              v-for="(row, index) in selectedRows"
              :key="index"
              closable
              @close="handleRemoveRecipient(index)"
              type="info"
            >
              {{ row.name }}（{{ row.phone }}）
            </el-tag>
            <div v-if="selectedRows.length === 0" class="empty-recipient">
              暂无通知对象，请先选择学员
            </div>
          </div>
        </el-form-item>

        <el-form-item label="通知类型" prop="noticeType">
          <el-radio-group v-model="noticeForm.noticeType">
            <el-radio label="sms">短信通知</el-radio>
            <el-radio label="system">站内通知</el-radio>
            <el-radio label="both">短信+站内通知</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="通知内容" prop="content">
          <el-input
            v-model="noticeForm.content"
            type="textarea"
            rows="5"
            placeholder="请输入通知内容（短信不超过70字）"
            @input="handleContentInput"
          />
          <div class="content-count">{{ noticeForm.content.length }}/70</div>
        </el-form-item>

        <el-form-item label="发送时间" prop="sendTime">
          <el-radio-group v-model="noticeForm.sendTime">
            <el-radio label="immediate">立即发送</el-radio>
            <el-radio label="timed">定时发送</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item
          label="定时时间"
          prop="timedSendTime"
          v-if="noticeForm.sendTime === 'timed'"
        >
          <el-date-picker
            v-model="noticeForm.timedSendTime"
            type="datetime"
            placeholder="选择发送时间"
            style="width: 100%;"
            :disabled-date="disabledDate"
          />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="showNoticeDialog = false">取消</el-button>
        <el-button
          type="primary"
          @click="handleSendNotice"
          :disabled="selectedRows.length === 0"
        >
          确认发送
        </el-button>
      </div>
    </el-dialog>

    <!-- 学员备注弹窗 -->
    <el-dialog
      :title="remarkTitle"
      :visible.sync="remarkVisible"
      width="800px"
      @close="resetRemarkForm"
      class="dialog-remark"
    >
      <el-form ref="remarkForm" :model="remarkForm" label-width="80px" :rules="remarkRules">
        <!-- 备注输入框 -->
        <el-form-item label="备注" prop="remarks">
          <el-input
            v-model="remarkForm.remarks"
            type="textarea"
            :rows="4"
            placeholder="请输入备注内容"
            style="width: 100%"
            maxlength="200"
            show-word-limit
          ></el-input>
        </el-form-item>

        <!-- 备注历史记录 -->
        <el-form-item label="备注历史">
          <el-table
            :data="remarkHistory"
            border
            style="width: 100%"
            :show-header="true"
            :loading="remarkLoading"
            empty-text="暂无备注记录"
            size="mini"
          >
            <el-table-column prop="time" label="时间" width="200" align="center"></el-table-column>
            <el-table-column prop="operator" label="备注人" width="150" align="center"></el-table-column>
            <el-table-column prop="content" label="备注内容" min-width="300" align="left"></el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="remarkVisible = false">取消</el-button>
        <el-button type="primary" @click="submitRemark" :loading="remarkSubmitting">提交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { selectCheckinDetails } from "@/api/training/ClassCheckin";
import { addCheckinRemark, batchUpdate } from "@/api/training/CheckinRecord";
import { listRemarksByParams, addRemarks } from "@/api/training/remarks";

export default {
  name: "SignManagementPage",
  data() {
    return {
      // 培训班信息
      classId: '',
      className: '',
      classCheckinId: '',
      trainingClassCode: '',
      checkinTime: '',
      checkinLocation: '',

      // 搜索表单
      searchForm: {
        name: "",
        phone: "",
        idCard: "",
        signStatus: ""
      },
      // 控制搜索区域显隐
      showSearch: true,
      // 表格选中行
      selectedRows: [],
      // 签到数据列表
      signList: [],
      // 分页配置
      pagination: {
        currentPage: 1,
        pageSize: 10
      },
      // 总数据量
      total: 0,
      // 列显隐配置
      visibleColumns: {
        selection: true,
        name: true,
        idCard: true,
        phone: true,
        signStatus: true,
        remark: true,
        operation: true
      },
      // 学员通知相关
      showNoticeDialog: false,
      noticeForm: {
        noticeType: "sms",       // 通知类型：sms|system|both
        content: "",             // 通知内容
        sendTime: "immediate",   // 发送时间：immediate|timed
        timedSendTime: ""        // 定时发送时间
      },
      noticeRules: {
        noticeType: [
          { required: true, message: "请选择通知类型", trigger: "change" }
        ],
        content: [
          { required: true, message: "请输入通知内容", trigger: "blur" },
          { max: 70, message: "通知内容不能超过70个字", trigger: "input" }
        ],
        timedSendTime: [
          { required: true, message: "请选择定时发送时间", trigger: "change" }
        ]
      },
      // 学员备注相关
      remarkVisible: false,
      remarkTitle: "学员备注",
      remarkForm: {
        remarks: "",
        classCheckinId: null
      },
      remarkHistory: [],
      remarkLoading: false,
      remarkSubmitting: false,
      remarkRules: {
        remarks: [{ required: true, message: "请输入备注内容", trigger: "blur" }]
      }
    };
  },
  created() {
    this.getList();
  },
  watch: {
    '$route.query.classId': {
      immediate: true,
      handler(newId) {
        const params = this.$route.params;
        this.classId = params.classId;
        this.className = params.className;
        this.classCheckinId = params.classCheckinId;
        this.trainingClassCode = params.trainingClassCode;
        this.checkinTime = params.checkinTime;
        this.checkinLocation = params.checkinLocation;
        this.getList();
      }
    }
  },
  computed: {
    paginatedList() {
      return this.signList;
    },
    totalCount() {
      return this.total;
    }
  },
  methods: {
    async getList() {
      if (!this.classId) return;

      try {
        const res = await selectCheckinDetails({
          classCheckinId: this.classCheckinId,
          studentName: this.searchForm.name,
          phoneNumber: this.searchForm.phone,
          idNumber: this.searchForm.idCard,
          checkinStatus: this.searchForm.signStatus,
          pageNum: this.pagination.currentPage,
          pageSize: this.pagination.pageSize
        });

        if (res.code === 200) {
          this.signList = res.rows.map(item => ({
            id: item.checkinRecordId || '',
            name: item.studentName || '',
            idCard: item.idNumber || '',
            phone: item.phoneNumber || '',
            signStatus: item.checkinStatus || '0',
            remark: item.checkinRemark || '',
            rawData: item
          }));
          this.total = res.total || 0;
        } else {
          this.$message.error(`获取数据失败：${res.msg || '未知错误'}`);
        }
      } catch (error) {
        console.error('请求签到记录失败：', error);
        this.$message.error('网络异常，请稍后重试');
      }
    },
    handleSearch() {
      this.pagination.currentPage = 1;
      this.getList();
      this.$message.success("搜索条件已应用");
    },
    handleReset() {
      this.searchForm = {
        name: "",
        phone: "",
        idCard: "",
        signStatus: ""
      };
      this.pagination.currentPage = 1;
      this.getList();
      this.$message.info("搜索条件已重置");
    },
    handleSelectionChange(val) {
      this.selectedRows = val;
    },
    handleSizeChange(val) {
      this.pagination.pageSize = val;
      this.pagination.currentPage = 1;
      this.getList();
      this.$message.info(`已切换为每页 ${val} 条`);
    },
    handleCurrentPageChange(val) {
      this.pagination.currentPage = val;
      this.getList();
    },
    handleExport() {
      this.$message.info("导出功能待实现");
    },
    handleBatchSetSign(is1) {
      if (this.selectedRows.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }

      const statusText = is1 ? "已签到" : "未签到";
      const checkinStatus = is1 ? "1" : "0";
      const currentTime = new Date();
      const names = this.selectedRows.map(row => row.name).join("、");

      const batchParams = this.selectedRows.map(row => ({
        checkinRecordId: row.id || "",
        classCheckinId: this.classCheckinId,
        studentId: row.rawData.studentId || "",
        studentName: row.name,
        idNumber: row.idCard,
        phoneNumber: row.phone,
        checkinStatus: checkinStatus,
        actualCheckinTime: this.formatUTCDate(currentTime)
      }));

      this.$confirm(`是否将“${names}”设为${statusText}?`, "系统提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          try {
            const res = await batchUpdate(batchParams);
            if (res.code === 200) {
              this.$message.success(`已将选中的${this.selectedRows.length}名学员设为${statusText}`);
              this.getList();
              this.$refs.signTable.clearSelection();
            } else {
              this.$message.error(`操作失败：${res.msg || '批量更新状态异常'}`);
            }
          } catch (error) {
            console.error("批量更新签到状态失败：", error);
            this.$message.error("网络异常，请稍后重试");
          }
        })
        .catch(() => {
          this.$message.info(`已取消批量设为${statusText}操作`);
        });
    },
    formatUTCDate(date) {
      const year = date.getUTCFullYear();
      const month = String(date.getUTCMonth() + 1).padStart(2, "0");
      const day = String(date.getUTCDate()).padStart(2, "0");
      const hours = String(date.getUTCHours()).padStart(2, "0");
      const minutes = String(date.getUTCMinutes()).padStart(2, "0");
      const seconds = String(date.getUTCSeconds()).padStart(2, "0");
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    handleSingleSetSign(row, is1) {
      const statusText = is1 ? "已签到" : "未签到";
      const checkinStatus = is1 ? "1" : "0";
      const currentTime = new Date();

      this.$confirm(`是否将“${row.name}”设为${statusText}?`, "系统提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          try {
            const singleParams = [
              {
                checkinRecordId: row.id || "",
                classCheckinId: this.classCheckinId,
                studentId: row.rawData.studentId || "",
                studentName: row.name,
                idNumber: row.idCard,
                phoneNumber: row.phone,
                checkinStatus: checkinStatus,
                actualCheckinTime: this.formatUTCDate(currentTime)
              }
            ];

            const res = await batchUpdate(singleParams);
            if (res.code === 200) {
              this.$message.success(`已将“${row.name}”设为${statusText}`);
              this.getList();
            } else {
              this.$message.error(`操作失败：${res.msg || '更新状态异常'}`);
            }
          } catch (error) {
            console.error(`单个更新${row.name}签到状态失败：`, error);
            this.$message.error("网络异常，请稍后重试");
          }
        })
        .catch(() => {
          this.$message.info(`已取消设为${statusText}操作`);
        });
    },
    // 学员备注相关方法
    async handleRemark() {
      if (this.selectedRows.length === 0) {
        return this.$message.warning("请选择1名学员进行备注");
      }
      if (this.selectedRows.length > 1) {
        return this.$message.warning("仅支持对单个学员进行备注");
      }

      const targetStudent = this.selectedRows[0];
      this.remarkForm.classCheckinId = targetStudent.id;
      this.remarkTitle = `学员【${targetStudent.name}】备注`;
      this.remarkLoading = true;
      console.log(this.remarkForm.classCheckinId)
      try {
        const res = await listRemarksByParams({
          foreignId: this.remarkForm.classCheckinId,
          remarkType: "6"
        });
        this.remarkHistory = res.rows.map(item => ({
          time: item.createTime,
          operator: item.createBy || "未知操作人",
          content: item.remarks
        }));
      } catch (err) {
        this.$message.error(`加载备注历史失败：${err.msg || "网络异常"}`);
        this.remarkHistory = [];
      } finally {
        this.remarkLoading = false;
        this.remarkVisible = true;
      }
    },
    resetRemarkForm() {
      this.$nextTick(() => {
        if (this.$refs.remarkForm) {
          this.$refs.remarkForm.resetFields();
        }
        this.remarkForm.remarks = "";
      });
    },
    async submitRemark() {
      this.$refs.remarkForm.validate(async (valid) => {
        if (!valid) return;

        this.remarkSubmitting = true;
        console.log(this.selectedRows[0])
        try {
          await addCheckinRemark({
            checkinRecordId:this.selectedRows[0].id,
            classCheckinId:this.selectedRows[0].rawData.classCheckinId,
            studentId:this.selectedRows[0].rawData.studentId,
            studentName:this.selectedRows[0].rawData.studentName,
            idNumber:this.selectedRows[0].rawData.idNumber,
            phoneNumber:this.selectedRows[0].rawData.phoneNumber,
            checkinStatus:this.selectedRows[0].rawData.checkinStatus,
            actualCheckinTime:this.selectedRows[0].rawData.actualCheckinTime,
            remarkType:"6",
            checkinRemark: this.remarkForm.remarks
          });

          this.$message.success("备注提交成功");
          this.remarkVisible = false;
          this.getList();
          this.$refs.signTable.clearSelection();
        } catch (err) {
          this.$message.error(`备注提交失败：${err.msg || "网络异常"}`);
        } finally {
          this.remarkSubmitting = false;
        }
      });
    },
    handleRefresh() {
      this.getList().then(() => {
        setTimeout(() => {
          this.$message.success("数据已刷新");
        }, 300);
      });
    },
    handleContentInput() {
      if (this.noticeForm.content.length > 70) {
        this.noticeForm.content = this.noticeForm.content.slice(0, 70);
      }
    },
    handleRemoveRecipient(index) {
      this.selectedRows.splice(index, 1);
    },
    disabledDate(time) {
      return time.getTime() < Date.now() - 8.64e7;
    },
    handleSendNotice() {
      this.$refs.noticeForm.validate(valid => {
        if (valid) {
          this.$message.loading("正在发送通知...", 0);

          setTimeout(() => {
            const params = {
              recipients: this.selectedRows.map(row => ({
                id: row.id,
                phone: row.phone,
                name: row.name
              })),
              type: this.noticeForm.noticeType,
              content: this.noticeForm.content,
              sendTime: this.noticeForm.sendTime === "immediate"
                ? new Date().toISOString()
                : new Date(this.noticeForm.timedSendTime).toISOString()
            };

            console.log("发送通知参数：", params);
            this.$message.success(`成功发送通知给 ${this.selectedRows.length} 名学员`);
            this.showNoticeDialog = false;
            this.$refs.noticeForm.resetFields();
            this.$refs.signTable.clearSelection();
          }, 1500);
        }
      });
    }
  }
};
</script>

<style scoped>
.sign-management-page {
  padding: 20px;
  background-color: #fff;
  min-height: calc(100vh - 40px);
  box-sizing: border-box;
}

/* 顶部信息栏 */
.top-info {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 20px;
  font-size: 14px;
  color: #333;
  flex-wrap: wrap;
}

.top-info span {
  padding: 4px 8px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

/* 搜索区域 */
.search-area {
  margin-bottom: 20px;
  padding: 16px;
  background-color: #f9f9f9;
  border-radius: 4px;
  box-shadow: 0 1px 2px rgba(0,0,0,0.05);
}

.search-form {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  align-items: center;
}

.search-input, .search-select {
  width: 180px;
}

/* 操作按钮区 */
.operation-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 20px;
  align-items: center;
}
.operation-buttons .el-button { padding: 6px 10px; }

/* 签到状态标签 */
.tag_1 {
  color: #4CAF50;
  background-color: rgba(76, 175, 80, 0.1);
  padding: 2px 6px;
  border-radius: 3px;
  font-weight: 500;
}
.tag_0 {
  color: #F44336;
  background-color: rgba(244, 67, 54, 0.1);
  padding: 2px 6px;
  border-radius: 3px;
  font-weight: 500;
}

/* 表格 */
.el-table {
  font-size: 13px;
}
.el-table th {
  background-color: #f5f7fa !important;
}

/* 学员通知弹窗样式 */
.recipient-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  max-height: 120px;
  overflow-y: auto;
  padding: 4px;
}

.empty-recipient {
  color: #999;
  padding: 8px 0;
  font-size: 13px;
}

.content-count {
  text-align: right;
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 学员备注弹窗样式 */
::v-deep .dialog-remark .el-textarea {
  width: 100%;
  margin-bottom: 8px;
}
::v-deep .dialog-remark .el-table {
  margin-top: 10px;
  font-size: 13px;
}
::v-deep .dialog-remark .el-table th {
  background-color: #f5f7fa !important;
}
::v-deep .dialog-remark .el-form-item {
  margin-bottom: 16px;
}

/* 响应式适配 */
@media (max-width: 768px) {
  .top-info {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  .search-input, .search-select {
    width: 100%;
  }
}
</style>
